package org.goyo.common.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;

public class JSONUtil {
	private static ObjectMapper objectMapper = new ObjectMapper();
	static{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
		setDateFormate(df);
	}
	public static void setDateFormate(DateFormat dateFormat) {
		objectMapper.setDateFormat(dateFormat);
		objectMapper.setSerializationInclusion(Inclusion.NON_NULL);
	}

	public static <T> T json2Obj(String json, Class<T> clazz) {
		try {
			return objectMapper.readValue(json, clazz);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static <T> T json2Obj(String json, TypeReference typeReference) {
		try {
			return objectMapper.readValue(json, typeReference);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static <T> T json2Obj(String json, JavaType javaType) {
		try {
			return objectMapper.readValue(json, javaType);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static String obj2Json(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> json2List(String json) {
		try {
			return json2Obj(json, List.class);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T,E> Map<T,E> json2Map(String json) {
		try {
			return json2Obj(json, Map.class);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
